﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace SIS.DataAccess.Ultilities
{
	/// <summary>
	/// Author: hieunv
	/// </summary>
	public class DataServices
	{
		public const string CONNECTION_STRING = "SIS";
		private static SqlConnection _connection = new SqlConnection(ConfigurationManager.ConnectionStrings[CONNECTION_STRING].ConnectionString);
		public static SqlConnection Connection
		{
			get
			{
				return _connection;
			}
		}

		private static DataServices _this;
		public static DataServices This
		{
			get
			{
				if (_this == null) _this = new DataServices();
				return _this;
			}
		}

		private DataServices()
		{

		}

		public static SqlConnection Open()
		{
			if (_connection.State != ConnectionState.Open)
			{
				_connection.Open();
			}
			return _connection;
		}

		public static void Close()
		{
			if (_connection.State == ConnectionState.Open)
			{
				_connection.Close();
			}
		}

		public static int ExecuteQuery(QueryType queryType, CommandType commandType, string query, List<SqlParameter> parameters, DataTable data)
		{
			try
			{
				Open();
				int i = 0;
				using (SqlCommand command = _connection.CreateCommand())
				{
					command.CommandText = query;
					command.CommandType = commandType;
					if (parameters != null)
					{
						foreach (SqlParameter parameter in parameters)
						{
							command.Parameters.Add(parameter);
						}
					}

					using (SqlDataAdapter adapter = new SqlDataAdapter())
					{
						switch (queryType)
						{
							case QueryType.SELECT:
							{
								adapter.SelectCommand = command;
								i = adapter.Fill(data);
							} break;
							case QueryType.INSERT:
							{
								adapter.InsertCommand = command;
								i = adapter.Update(data);
							} break;
							case QueryType.UPDATE:
							{
								adapter.UpdateCommand = command;
								i = adapter.Update(data);
							} break;
							case QueryType.DELETE:
							{
								adapter.DeleteCommand = command;
								i = adapter.Update(data);
							} break;
						}

					}
				}
				return i;
			}
			finally
			{
				Close();
			}			
		}
	}

	/// <summary>
	/// Author: hieunv
	/// </summary>
	public enum QueryType
	{
		SELECT = 0,
		INSERT = 1,
		UPDATE = 2,
		DELETE = 4,
	}
}
